package com.dftdla.server.handler;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dftdla.dao.service.ChatUserService;
import com.dftdla.jwt.utils.JwtUtil;
import com.dftdla.mq.publisher.RabbitMqPublisher;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author 14501
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class ElseMessageHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private RabbitMqPublisher publisher;
    @Resource
    private ChatUserService chatUserService;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String uuid = UUID.randomUUID().toString();
        long userId;
        try {
            log.warn("PROCESS_ID:{},服务器不处理的指令数据:{}",uuid,msg);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(msg));
            String token = (String) jsonObject.get("token");
            boolean auth = chatUserService.doAuth(token, ctx.channel());
            if(auth){
                userId = Long.parseLong(JwtUtil.parseJWT(token).getSubject());
                jsonObject.put("from",userId);
                ArrayList<Long> longs = new ArrayList<>();
                longs.add(Long.valueOf((String) jsonObject.get("to")));
                publisher.sendMsg(longs,jsonObject);
                log.warn("PROCESS_ID:{},服务器中转解析结果:{},已转发",uuid,jsonObject);
            }else{
                log.warn("PROCESS_ID:{},请求不合法",uuid);
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.warn("PROCESS_ID:{},不合法的请求数据",uuid);
        }
    }
}
